package com.nit.tools.pdf;

import com.google.common.collect.Lists;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class PDFBoxExample {

    public static void main(String[] args) {
        // 保存的pdf全路径
        String outPdfPath = "D://out.pdf";
        // pdf需要展示的文本
        String text = "这是一些文本";
        // pdf中表格需要填充的数据
        List<List<String>> data = Lists.newArrayList();
        // 创建一个新的PDF文档
        try (PDDocument newDocument = new PDDocument()) {
            ClassLoader classLoader = PDFBoxExample.class.getClassLoader();
            String[][] content = new String[data.size() + 1][8];
            content[0] = new String[]{"列1", "列2", "列3", "列4", "列5", "列6", "列7", "列8"};
            for (int i = 0; i < data.size(); i++) {
                List<String> dto = data.get(i);
                content[i + 1] = new String[]{dto.get(0), dto.get(1), dto.get(2), dto.get(3), dto.get(4), dto.get(5), dto.get(6), dto.get(7)};
            }

            PDPage pdPage = new PDPage();
            // 加载自定义字体
            InputStream inputStream = classLoader.getResourceAsStream("");
            PDFont font = PDType0Font.load(newDocument, new File("Z:\\nit-random-tools\\src\\main\\resources\\ttfs\\Alibaba_PuHuiTi_2.0_35_Thin_35_Thin.ttf"));
            // 创建一个新的内容流，用于向页面添加内容
            try (PDPageContentStream contentStream = new PDPageContentStream(newDocument, pdPage)) {

                // 开始写文本
                contentStream.beginText();
                //设置文本字体
                contentStream.setFont(font, 12);
                contentStream.newLineAtOffset(100, 700);
                contentStream.showText(text);
                // 结束文本块
                contentStream.endText();

                // 在文本之后 绘制表格

                drawTable(contentStream, 500, 10, content, font, 7);
            }
            newDocument.addPage(pdPage);
            // 保存新的PDF文档
            newDocument.save(outPdfPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 绘制表格的方法
     *
     * @param contentStream PDPageContentStream对象，用于在PDF页面上绘制内容
     * @param y             表格的起始y坐标，即表格的顶部位置
     * @param margin        表格的左边距
     * @param content       表格的内容，一个二维字符串数组，表示表格的行和列
     * @param font          PDFont对象，表示文本的字体
     * @param fontSize      文本的字体大小
     * @throws IOException IO异常
     */
    private static void drawTable(PDPageContentStream contentStream,
                                  float y, float margin,
                                  String[][] content, PDFont font, int fontSize) throws IOException {
        final int rows = content.length;
        final int cols = content[0].length;
        final float rowHeight = 20f;
        // 边距
        final float cellMargin = 5f;

        // 计算每列的最大宽度
        float[] colMaxWidths = new float[cols];
        for (int i = 0; i < cols; i++) {
            for (String[] row : content) {
                float textWidth = font.getStringWidth(row[i]) / 1000 * fontSize;
                if (textWidth > colMaxWidths[i]) {
                    colMaxWidths[i] = textWidth;
                }
            }
            // 为每列的文本添加边距
            colMaxWidths[i] += 2 * cellMargin;
        }

        // 检查表格总宽度是否超出页面宽度
        float totalColWidth = 0f;
        for (float width : colMaxWidths) {
            totalColWidth += width;
        }

        // 绘制行
        float nexty = y;
        for (int i = 0; i <= rows; i++) {
            contentStream.moveTo(margin, nexty);
            contentStream.lineTo(margin + totalColWidth, nexty);
            contentStream.stroke();
            nexty -= rowHeight;
        }

        // 绘制列
        float nextx = margin;
        for (int i = 0; i < cols; i++) {
            contentStream.moveTo(nextx, y);
            contentStream.lineTo(nextx, y - rowHeight * rows);
            contentStream.stroke();
            nextx += colMaxWidths[i];
        }
        // 绘制最后一条列线
        contentStream.moveTo(nextx, y);
        contentStream.lineTo(nextx, y - rowHeight * rows);
        contentStream.stroke();

        // 添加文本到表格
        float textx = margin + cellMargin;
        // 从字体度量中获取字体的上升和下降值，以确保文本居中
        float fontHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
        float fontDescent = font.getFontDescriptor().getDescent() / 1000 * fontSize;
        // 计算文本基线到单元格顶部的距离
        // 调整垂直居中
        float texty = y - (rowHeight / 2) - (fontHeight / 2) - fontDescent;
        for (String[] row : content) {
            for (int i = 0; i < row.length; i++) {
                String cell = row[i];
                contentStream.beginText();
                contentStream.setFont(font, fontSize);
                contentStream.newLineAtOffset(textx, texty);
                contentStream.showText(cell);
                contentStream.endText();
                textx += colMaxWidths[i];
            }
            texty -= rowHeight;
            textx = margin + cellMargin;
        }
    }
}

